<!-- 安全检查 -->
<template>
<div class="securityMain">
    <map-container ref="mapContainer"></map-container>
    <!-- 搜索框 -->
    <div style="width: calc(100% - 90px); margin: 10px 20px; height: 32px; background: #fff; z-index: 99; position: absolute; left: 10px; border-radius: 5px; border: 1px solid #f3f3f3;">
        <!-- 下拉框部分 -->
        <div style="float: left; height: 20px; line-height: 20px; width: 75px; margin: 5px 0px; border-right: 1px solid #f3f3f3;" @click="showPicker = true">
            <div style="height: 100%;">
                <div style="float: left;line-height: 100%;width:16px;">
                    <img src="https://nfzjszlb.jst.zj.gov.cn/security/xiala.png" />
                </div>
                <div style="width: calc(100% - 32px); float: left; font-size: 14px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">{{form.cityname}}</div>
            </div>
        </div>
        <!-- 文本框部分 -->
        <div style="float: left; height: 32px; line-height: 32px; width: calc(100% - 120px);">
            <van-search v-model="form.propertyPerson" placeholder="请输入户主姓名" @search="_searchData('')" @clear="_searchClear">
            </van-search>
        </div>
        <!-- 搜索 -->
        <div style="height: 20px; float: left; float: right; padding: 0 5px; margin-top: 6px; border-left: 1px solid #f3f3f3;" @click="show1 = true">
            <img src="../../../static/imgs/topsearch/shaixuan.png" />
        </div>
    </div>
    <!-- 列表 -->
    <div style=" width: 32px; height: 32px; background: #fff; z-index: 99; position: absolute; right: 20px; top: 10px; border-radius: 5px; border: 1px solid #f3f3f3;" @click="_tiaoZhuan">
        <div style="text-align: center;">
            <img style="height: 12px;" src="https://nfzjszlb.jst.zj.gov.cn/security/liebiao.png" />
        </div>
        <div style="text-align: center;font-size: 10px;line-height: 16px;">列表</div>
    </div>
    <!-- 图例 -->
    <legend-tool ref="legendTool" :legendDatas="legendDatas"></legend-tool>
    <!-- 筛选 -->
    <van-popup v-model="show1" closeable title="筛选" position="bottom" show-cancel-button>
        <div style="height: 45px;line-height: 45px;font-size:16px;text-align: center;border-bottom: 1px solid #ccc;color: black;font-weight: bold ">
            筛选</div>
        <div class="searchWrap" style="">
            <van-field label-width="4em" v-model="form.cityname" is-link readonly label="所属区域" placeholder="请选择所属区域" @click="showPicker = true" />
            <van-field label-width="4em" name="radio" label="核查结论">
                <template #input>
                    <van-radio-group v-model="form.inspectResult" direction="horizontal">
                        <van-radio name="0">基本安全</van-radio>
                        <van-radio name="1">存在风险</van-radio>
                        <van-radio name="3">危房正在整治中</van-radio>
                        <van-radio name="4">已拆除</van-radio>
                    </van-radio-group>
                </template>
            </van-field>
            <van-field label-width="4em" name="radio" label="房屋用途">
                <template #input>
                    <van-radio-group v-model="form.houseUsage" direction="horizontal">
                        <van-radio name="1">经营性自建房</van-radio>
                        <van-radio name="2">其他自建房</van-radio>
                    </van-radio-group>
                </template>
            </van-field>
            <van-field label-width="4em" name="radio" label="数据来源">
                <template #input>
                    <van-radio-group v-model="form.dataSource" direction="horizontal">
                        <van-radio name="0">网格巡查</van-radio>
                        <van-radio name="2">农户提交</van-radio>
                    </van-radio-group>
                </template>
            </van-field>
            <van-field label-width="4em" name="radio" label="核查时间">
                <template #input>
                    <van-field style="width: calc(50% - 10px);float: left;padding: 0;" :border="false" label-width="0" v-model="form.inspectStaterDate" clearable label="" placeholder="请选择开始时间" @focus="showStart = true" />
                    <span style="float: left;line-height: 24px;">-</span>
                    <van-field style="width: calc(50% - 10px);float: left;padding: 0;" :border="false" label-width="0" v-model="form.inspectEndDate" clearable label=" " placeholder="请选择结束时间" @focus="showEnd = true" />
                </template>
            </van-field>
            <!-- 开始时间控件 -->
            <van-popup v-model="showStart" position="bottom">
                <van-datetime-picker v-model="currentDate" type="date" @confirm="_confirm" @cancel="_cancel" />
            </van-popup>
            <!-- 结束时间控件 -->
            <van-popup v-model="showEnd" position="bottom">
                <van-datetime-picker v-model="currentDate1" type="date" @confirm="_confirm1" @cancel="_cancel1" />
            </van-popup>
        </div>
        <div style="text-align: center;margin-bottom: 10px;">
            <van-button plain type="info" style="width: 47%;" @click="_restForm()">重置</van-button>
            <van-button plain style="width: 47%;" @click="_sureForm()">确定</van-button>
        </div>
    </van-popup>
    <!-- 区域下拉框-弹框 -->
    <van-popup v-model="showPicker" position="bottom">
        <van-cascader v-model="form.citycode" title="选择所属区域" :options="options" @change="_onChange" @finish="_onFinish" :closeable="false" style="position: relative;" />
        <span style="position: absolute; top: 0%; right: 10px;font-size: 14px;height: 48px;line-height: 48px;" @click="_close">确定</span>
    </van-popup>
    <!-- 搜索结果-底部弹框 -->
    <div v-show="showTK" class="sousuo-content" style="width:100vw;height:40vh;background:#ffffff;z-index:99;position: fixed;bottom: 0;">
        <div style="height: 4vh; background: #1989fa;" @click="_closeTK()">
            <img src="https://nfzjszlb.jst.zj.gov.cn/security/close.png" style="margin:1vh 2vw;float: right;" />
        </div>
        <div style="height:36vh;overflow-y: auto;">
            <van-list v-model="loading" :offset="4" :finished="finished" @load="_onLoad" finished-text="没有更多了" class="toBeCheckedList-middle1">
                <van-cell v-for="(item, index) in ListDataOption" :key="index" @click="_oneListClick(item)">
                    <ul class="toBeCheckedList-middle">
                        <li class="toBeCheckedList-middle2">
                            户主姓名：{{ item.propertyPerson }}
                            <span style="float: right">{{ item.currentStatus }} </span>
                        </li>
                        <li class="toBeCheckedList-middle4">自建房排查编号：{{ item.checkNumber }}</li>
                        <li class="toBeCheckedList-middle4">房屋用途：{{ item.houseUsage }}</li>
                        <li class="toBeCheckedList-middle4">问题来源：{{ item.dataSource }}</li>
                        <li class="toBeCheckedList-middle4">巡查时间：{{ item.patrolDate }}</li>
                        <li class="toBeCheckedList-middle4">地址：{{ item.belongCity }}{{ item.belongCountry }}{{ item.belongTown }}{{ item.belongVillage }}</li>
                    </ul>
                </van-cell>
            </van-list>
        </div>
    </div>

</div>
</template>

<script>
import dd from 'gdt-jsapi'
import Pubsub from 'pubsub-js'
import * as api from '../../utils/api_gis'
import {
    GetAdministrative,
    getDatalistForTree,
    housePublichouseRemoldUnitBuildinspectList,
} from '../../utils/api'
import * as esriLoader from "esri-loader";
import MapManager from "../../core/mapManager"
import MapContainer from './MapContainer'
import legendTool from "./public/legendTool.vue"
export default {
    name: "securityMain",
    data() {
        return {
            //详情跳转后的回显
            rowguid: "",
            isIquery: false,
            ifEcho: false,
            //初始化需要的相关参数
            legendDatas: [{
                    title: "待核查",
                    color: "#FFA500"
                },
                {
                    title: "已核查",
                    color: "#40E0D0"
                },
            ],
            showPicker: false,
            citycode: "",
            cityname: "",
            // CountyData: [],
            options: [],
            //底部详情框
            showTK: false,
            startPage: 0,
            loading: false,
            finished: false,
            ListDataOption: [],
            //筛选---新增需求
            show1: false,
            showStart: false,
            showEnd: false,
            currentDate: new Date(),
            currentDate1: new Date(),
            dataSource: '',
            form: {
                cityname: "选择区域",
                citycode: "",
                propertyPerson: "",
                dataSource: null,
                inspectEndDate: null,
                houseUsage: null,
                inspectResult: null,
                inspectStaterDate: null,
            },
            //当前定位
            geometryHX: null,

        };
    },

    components: {
        MapContainer,
        legendTool,
    },

    computed: {},
    //注意：修改组件请添加对应的修改版本、日期、功能、注释！！！！
    //方法：方法命名请以下划线_开头！！！！
    //其它项复制粘贴过来的代码，请将无用的参数删除，一个js类用到一个方法不要粘整个js过来！！！！
    methods: {
        //初始化判断是store是否存在，判断是第一次打开，还是返回回显
        _echo() {
            if (JSON.stringify(this.$store.state.securityMainSearch) != "{}" && this.$store.state.securityMainSearch != undefined) {
                this.form = this.$store.state.securityMainSearch.form
                if (this.$store.state.securityMainSearch.isIquery == true) {
                    Pubsub.publish("openQuqry");
                    this._searchData(this.$store.state.securityMainSearch.rowguid)
                } else {
                    this._searchData("")
                }
                this.geometryHX = this.$store.state.securityMainSearch.geometryHX
                this._locationHX(this.geometryHX)
                this.ifEcho = false
            }
        },
        //获取url地址中的某一个参数值
        _getUrlParam(paraName) {
            var url = decodeURI(document.location.toString());
            var arrObj = url.split("?");

            if (arrObj.length > 1) {
                var arrPara = arrObj[1].split("&");
                var arr;
                for (var i = 0; i < arrPara.length; i++) {
                    arr = arrPara[i].split("=");
                    if (arr != null && arr[0] == paraName) {
                        return arr[1];
                    }
                }
                return "";
            } else {
                return "";
            }
        },
        //列表跳转
        _tiaoZhuan() {
            this.ifEcho = false;
            this.$router.push({
                path: '/toBeCheckedList'
            })
        },
        //所属区域检查
        _getXianOpenDataView: async function (data) {
            if (window.localStorage.getItem('citycode') != "330000000000") {
                this.options = [{
                    text: window.localStorage.getItem('cityName'),
                    value: window.localStorage.getItem('citycode'),
                    isHasChild: true
                }]
            }
            const res = await getDatalistForTree(data)
            res.data.data.forEach((item) => {
                let obj = {
                    text: item.cityname,
                    value: item.citycode,
                }
                if (item.citycode.toString().substring(9, 12) !== "000") {

                } else {
                    obj['children'] = []
                }
                this.options.push(obj)
            })
        },
        _onChange({
            value,
            selectedOptions,
            tabIndex
        }) {
            if (value.toString().substring(9, 12) !== "000" || selectedOptions[0].isHasChild) {} else {
                this._getXZQH(value, selectedOptions, tabIndex)
            }
            this._onFinish({
                value,
                selectedOptions,
                tabIndex
            })
        },
        _onFinish({
            value,
            selectedOptions,
            tabIndex
        }) {
            this.form.cityname = selectedOptions[selectedOptions.length - 1].text;
            this.form.citycode = value
            this._locationQH(value)
        },
        //清空
        _close() {
            this.showPicker = false;
            this.showTK = false;
            this.startPage = 0;
            this.ListDataOption = [];
        },
        _getXZQH: async function (value, selectedOptions, tabIndex) {
            const res = await GetAdministrative(value)
            selectedOptions[tabIndex].children = []
            if (res.data.data.length > 0) {
                res.data.data.forEach((element) => {
                    let obj = {
                        text: element.cityname,
                        value: element.citycode
                    }
                    if (element.citycode.toString().substring(9, 12) !== "000") {} else {
                        obj['children'] = []
                    }
                    selectedOptions[tabIndex].children.push(obj)
                })
            }
        },
        _closeTK() {
            this.showTK = false;
            this.ListDataOption = [];
            this.rowguid = "";
            this.isIquery = false;
        },
        //······························
        //根据头部选择中的区划进行定位
        _locationQH(code) {
            const self = this
            code += ""
            if (code.substring(0, 12) == "330000000000") { //省级
                if (window.g.MapConfiguration.InitExtent) {
                    let initExtent = new self.Extent(window.g.MapConfiguration.InitExtent);
                    self.geometryHX = initExtent //.center;
                    self.mapView.goTo({
                        target: initExtent.center,
                        // zoom: 13
                    }, {
                        easing: "ease-out",
                        duration: 1000
                    });
                }
            } else if (code.substring(4, 12) == "00000000") { //市级
                let city = self.cityDivisions.find(item => {
                    return item.attributes.code == code.substring(0, 6)
                })
                self.geometryHX = city.geometry.extent //.center
                self.mapView.goTo({
                    target: city.geometry.extent.center,
                    // zoom: 13
                }, {
                    easing: "ease-out",
                    duration: 1000
                });
            } else if (code.substring(6, 12) == "000000") { //区县(/有的code没有后六位有的有)
                let quxian = self.blockDivisions.find(item => {
                    return item.attributes.code == code.substring(0, 6)
                })
                if (typeof (quxian) == "undefined") {
                    quxian = self.blockDivisions.find(item => {
                        return item.attributes.code == code
                    })
                }
                self.geometryHX = quxian.geometry.extent //.center
                self.mapView.goTo({
                    target: quxian.geometry.extent.center,
                    // zoom: 16
                }, {
                    easing: "ease-out",
                    duration: 1000
                });
            } else { //村镇
            }
        },
        //回显定位
        _locationHX(geometryHX) {
            const self = this
            this.$nextTick(() => {
                setTimeout(() => {
                    self.mapView.goTo({
                        target: geometryHX.center,
                        // zoom: 13
                    }, {
                        easing: "ease-out",
                        duration: 1000
                    });
                }, 2000)
            })
        },
        //加载矢量瓦片图层
        _addLayers() {
            const self = this
            let player = new self.MapImageLayer({
                title: window.g.SecurityCheck.layer.title,
                id: window.g.SecurityCheck.layer.title + "_SecurityCheck",
                url: window.g.SecurityCheck.layer.url,
            });
            self.mapView.map.add(player)
        },
        //搜索
        _searchData(yhfwbh) {
            // if (this.form.propertyPerson == "" && yhfwbh == "") {
            //     return
            // }
            this.startPage = 0
            this.ListDataOption = []
            this._onLoad(yhfwbh)
        },
        _onLoad(yhfwbh) {
            this.startPage += 1
            this._getData(yhfwbh)
        },
        //获取查询结果
        async _getData(yhfwbh) {
            const self = this
            //注意：yhfwbh传参，表示当前是i查询过来的，直接用房屋统一编码进行查询即可。否则就是搜索框的查询
            let parm = null
            if (yhfwbh != "" && yhfwbh != undefined) {
                //i查询
                parm = {
                    pageNo: this.startPage,
                    pageSize: 20,
                    checkNumber: yhfwbh //房屋编号
                }
            } else {
                //搜索框
                let citycode = self.form.citycode + ""
                parm = {
                    pageNo: this.startPage,
                    pageSize: 20,
                    cityCode: citycode,
                    // propertyPerson: this.form.propertyPerson,
                }
                if (this.form.propertyPerson != "") {
                    parm.propertyPerson = this.form.propertyPerson
                }
                for (var i in this.form) {
                    if (this.form[i]) {
                        if (i == 'citycode') {
                            parm[i] = this.form[i].toString().replace(/(0+)$/g, '')
                        } else if (i == 'inspectStaterDate') {
                            parm[i] = this.form[i] + " 00:00:00"
                        } else if (i == 'inspectEndDate') {
                            parm[i] = this.form[i] + " 23:59:59"
                        } else {
                            parm[i] = this.form[i]
                        }
                    }
                }
            }

            self.showTK = true
            let webResult = await housePublichouseRemoldUnitBuildinspectList(parm)
            this.loading = false
            let pageList = webResult.data.data.pageList
            if (pageList.length > 0) {
                this.finished = false
                this.ListDataOption.push(...pageList)
            } else {
                this.finished = true
            }
            if (this.ListDataOption.length >= webResult.data.data.totalCount) {
                this.finished = true
            }
        },
        //搜索清空
        _searchClear() {
            this.showTK = false
            this.form.propertyPerson = ""
            this.ListDataOption = []
        },
        //底部弹框单行单击跳转
        _oneListClick(item) {
            //跳转
            this.ifEcho = true;
            this.$router.push({
                path: '/toBeChecked',
                query: {
                    data: JSON.stringify(item),
                    type: item.currentStatus == "未核查" ? 0 : 1,
                    isMap: true,
                }
            })
        },

        //·············新增需求--条件筛选··················
        //日期格式
        _formatDate(date) {
            return `${date.getFullYear()}-${(date.getMonth() + 1) < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1}-${date.getDate() < 10 ? ('0' + date.getDate()) : date.getDate()}`
        },
        //确认开始日期
        _confirm(date) {
            this.showStart = false
            this.form.inspectStaterDate = this._formatDate(this.currentDate)
        },
        //确认结束日期
        _confirm1(date) {
            this.showEnd = false
            this.form.inspectEndDate = this._formatDate(this.currentDate1)
        },
        _cancel() {
            this.showStart = false;
            this.form.inspectStaterDate = ""
        },
        _cancel1() {
            this.showEnd = false
            this.form.inspectEndDate = ""
        },
        //重置
        _restForm() {
            for (var i in this.form) {
                this.form[i] = null;
            }
            this.form.citycode = this.citycode
            this.form.cityname = this.cityname
        },
        //确定
        _sureForm() {
            this.show1 = false;
            this.startPage = 0
            this.ListDataOption = []
            this._searchData("")
        },

    },

    beforeRouteLeave(to, from, next) {
        if (this.ifEcho) {
            //离开路由时把位置存起来
            // this.$store.state.securityMainSearch = this.form
            this.$store.state.securityMainSearch = {
                form: this.form,
                isIquery: this.isIquery,
                geometryHX: this.geometryHX,
                rowguid: this.rowguid
            }
        } else {
            this.$store.state.securityMainSearch = {}
        }
        next()
    },

    mounted() {
        const self = this

        dd.ready(function () {
            dd.setTitle({
                    title: '安全核查',
                })
                .then((res) => {})
                .catch((err) => {
                    console.error(err)
                })
        })
        // //1、获取当前用户级别
        // self.citycode = window.localStorage.getItem('citycode')
        // self.cityname = window.localStorage.getItem('cityName')
        // if (self.citycode == null) {
        //     self.citycode = self._getUrlParam("citycode")
        // }
        // if (self.cityname == null) {
        //     self.cityname = self._getUrlParam("cityname")
        // }

        // if (self.citycode == "330000000000") {
        //     self.form.citycode = "441300000000"
        //     self.form.cityname = "杭州市"
        // } else {
        //     self.form.citycode = self.citycode
        //     self.form.cityname = self.cityname
        // }
        // // self._locationQH(value)
        // self._getXianOpenDataView(self.citycode)
        MapManager.getMapViewByIDAsy("mainMap").then((mapView) => {
            self.mapView = mapView;
            esriLoader
                .loadModules([
                    "esri/layers/MapImageLayer",
                    "esri/layers/FeatureLayer",
                    "esri/layers/GraphicsLayer",
                    "esri/Graphic",
                    "esri/geometry/Extent",
                    "esri/geometry/Point",
                    "esri/geometry/Polyline",
                    "esri/geometry/Polygon",
                    "esri/core/watchUtils",
                ])
                .then(
                    ([
                        MapImageLayer,
                        FeatureLayer,
                        GraphicsLayer,
                        Graphic,
                        Extent,
                        Point,
                        Polyline,
                        Polygon,
                        watchUtils,
                    ]) => {
                        self.MapImageLayer = MapImageLayer;
                        self.FeatureLayer = FeatureLayer;
                        self.GraphicsLayer = GraphicsLayer;
                        self.Graphic = Graphic;
                        self.Extent = Extent
                        self.Point = Point;
                        self.Polyline = Polyline;
                        self.Polygon = Polygon;
                        self.watchUtils = watchUtils;
                        //添加市级、区县要素
                        self.cityDivisions = MapManager.getAdministrativeDivisions()
                        self.blockDivisions = MapManager.getAdministrativeDivisions(1)
                        self._addLayers()

                        //1、获取当前用户级别
                        self.citycode = window.localStorage.getItem('citycode')
                        self.cityname = window.localStorage.getItem('cityName')
                        if (self.citycode == null) {
                            self.citycode = self._getUrlParam("citycode")
                        }
                        if (self.cityname == null) {
                            self.cityname = self._getUrlParam("cityname")
                        }

                        if (self.citycode == "330000000000") {
                            self.form.citycode = "441300000000"
                            self.form.cityname = "杭州市"
                        } else {
                            self.form.citycode = self.citycode
                            self.form.cityname = self.cityname
                        }
                        self.$nextTick(() => {
                            setTimeout(() => {
                                self._locationQH(self.form.citycode)
                            }, 1000)
                        })
                        self._getXianOpenDataView(self.citycode)
                    }
                );
        });
        self.mapPopupFeatureHander = Pubsub.subscribe("mapPopupFeature", (msg, data) => {
            if (data) {
                self.isIquery = true;
                self.geometryHX = data.geometry.extent
                self.rowguid = data.attributes['yhfwbh']; //用于存放房屋唯一编码，用于详情后的回显
                self._searchData(data.attributes['yhfwbh'])
            }
        })
        self.colseBottomTKHander = Pubsub.subscribe("closeBottomTK", (msg, data) => {
            self.showTK = false
            self.ListDataOption = []
        })
        self.clearIQuqryHander = Pubsub.subscribe("clearIQuqry", (msg, data) => {
            self.rowguid = ""
            self.geometryHX = null
        })
        // self.gotoFeatureHander = Pubsub.subscribe("gotoFeature", (msg, data) => {
        //     self.form.citycode = data.attributes.code + "000000"
        //     self.form.cityname = data.attributes.name
        // })
        //2、是否需要回显
        self.$nextTick(() => {
            setTimeout(() => {
                self._echo()
            }, 2000);
        })

    },

    beforeDestroy() {
        this.mapView.graphics.removeAll()
    },

}
</script>

<style lang="scss">
.securityMain .van-search {
    padding: 0 0;
    height: 30px;
}

.securityMain .van-search__content {
    background: #ffffff;
    height: 30px;
}

.securityMain .van-search .van-cell {
    padding: 2px 0;
}

.securityMain .van-cell {
    line-height: 30px;
}

.securityMain .van-field__left-icon {
    line-height: 30px;
}

.securityMain .van-cell__value {
    line-height: 30px;
}
</style>
